<template>
  <div class="time-arrangement-container">
    <!-- 页面头部 -->
    <div class="arrangement-header">
      <div class="header-content">
        <div class="ancient-title">值班时间安排</div>
        <div class="header-subtitle">阴曹地府 · 时间规划与班次管理</div>
      </div>
    </div>

    <!-- 路由信息 -->
    <div class="route-info">
      <a-breadcrumb>
        <a-breadcrumb-item
          ><router-link to="/management"><ApartmentOutlined />机构管理</router-link></a-breadcrumb-item
        >
        <a-breadcrumb-item
          ><router-link to="/management/duty-schedule"><ScheduleOutlined />值班排班系统</router-link></a-breadcrumb-item
        >
        <a-breadcrumb-item><ClockCircleOutlined />{{ $route.meta.title }}</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <!-- 时间安排管理 -->
    <a-row :gutter="24">
      <a-col :xs="24" :lg="16">
        <a-card title="排班时间表" :bordered="false">
          <template #extra>
            <a-space>
              <a-button type="primary" @click="showCreateShiftModal"> <PlusOutlined />新建班次 </a-button>
              <a-button @click="exportSchedule"> <ExportOutlined />导出排班 </a-button>
            </a-space>
          </template>

          <!-- 周历视图 -->
          <div class="weekly-calendar">
            <div class="calendar-header">
              <div class="time-navigation">
                <a-button @click="previousWeek"><LeftOutlined /></a-button>
                <span class="current-week">{{ currentWeekRange }}</span>
                <a-button @click="nextWeek"><RightOutlined /></a-button>
              </div>
              <a-radio-group v-model:value="viewMode" @change="handleViewModeChange">
                <a-radio-button value="week">周视图</a-radio-button>
                <a-radio-button value="month">月视图</a-radio-button>
              </a-radio-group>
            </div>

            <div class="calendar-body">
              <table class="schedule-table">
                <thead>
                  <tr>
                    <th>时间</th>
                    <th v-for="day in weekDays" :key="day">{{ day }}</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="timeSlot in timeSlots" :key="timeSlot.time">
                    <td class="time-cell">{{ timeSlot.time }}</td>
                    <td v-for="(day, dayIndex) in weekDays" :key="day" class="schedule-cell">
                      <div v-for="shift in getShiftsForTimeAndDay(timeSlot.time, dayIndex)" :key="shift.id" class="shift-block" :class="shift.type" @click="editShift(shift)">
                        <div class="shift-info">
                          <div class="shift-department">{{ shift.department }}</div>
                          <div class="shift-personnel">{{ shift.personnel.length }}人</div>
                        </div>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </a-card>
      </a-col>

      <a-col :xs="24" :lg="8">
        <a-space direction="vertical" size="large" style="width: 100%">
          <!-- 班次模板 -->
          <a-card title="班次模板" size="small" :bordered="false">
            <div class="shift-templates">
              <div v-for="template in shiftTemplates" :key="template.id" class="template-item">
                <div class="template-info">
                  <h4 class="template-name">{{ template.name }}</h4>
                  <p class="template-time">{{ template.startTime }} - {{ template.endTime }}</p>
                  <div class="template-departments">
                    <a-tag v-for="dept in template.departments" :key="dept" size="small">{{ dept }}</a-tag>
                  </div>
                </div>
                <div class="template-actions">
                  <a-button type="link" size="small" @click="applyTemplate(template)">应用</a-button>
                </div>
              </div>
            </div>
          </a-card>

          <!-- 时间统计 -->
          <a-card title="时间统计" size="small" :bordered="false">
            <div class="time-stats">
              <div class="stat-item">
                <span class="stat-label">本周总班次：</span>
                <span class="stat-value">{{ timeStats.totalShifts }}个</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">覆盖时间：</span>
                <span class="stat-value">{{ timeStats.coverageHours }}小时</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">参与部门：</span>
                <span class="stat-value">{{ timeStats.departments }}个</span>
              </div>
            </div>
          </a-card>
        </a-space>
      </a-col>
    </a-row>

    <!-- 新建班次弹窗 -->
    <a-modal v-model:open="createShiftModalVisible" title="新建班次" @ok="handleCreateShift" width="600px">
      <a-form ref="shiftFormRef" :model="shiftForm" :rules="shiftRules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="开始时间" name="startTime">
              <a-time-picker v-model:value="shiftForm.startTime" format="HH:mm" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="结束时间" name="endTime">
              <a-time-picker v-model:value="shiftForm.endTime" format="HH:mm" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="值班部门" name="department">
          <a-select v-model:value="shiftForm.department" placeholder="选择部门">
            <a-select-option v-for="dept in allDepartments" :key="dept.id" :value="dept.name">
              {{ dept.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="值班日期" name="dates">
          <a-checkbox-group v-model:value="shiftForm.dates">
            <a-row>
              <a-col :span="8" v-for="(day, index) in weekDays" :key="day">
                <a-checkbox :value="index">{{ day }}</a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-form-item>

        <a-form-item label="班次类型" name="type">
          <a-radio-group v-model:value="shiftForm.type">
            <a-radio value="regular">常规班</a-radio>
            <a-radio value="overtime">加班</a-radio>
            <a-radio value="emergency">紧急班</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { HomeOutlined, ApartmentOutlined, ScheduleOutlined, ClockCircleOutlined, PlusOutlined, ExportOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons-vue'

// 响应式数据
const viewMode = ref('week')
const currentWeek = ref(new Date())
const createShiftModalVisible = ref(false)
const shiftFormRef = ref()

// 周历数据
const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
const timeSlots = ref([{ time: '00:00-06:00' }, { time: '06:00-12:00' }, { time: '12:00-18:00' }, { time: '18:00-24:00' }])

// 部门数据
const allDepartments = ref([
  { id: 1, name: '第一殿秦广王府' },
  { id: 2, name: '第二殿楚江王府' },
  { id: 5, name: '第五殿阎罗王府' },
  { id: 10, name: '第十殿转轮王府' }
])

// 排班数据
const shifts = ref([
  {
    id: 1,
    department: '第一殿',
    type: 'regular',
    timeSlot: '06:00-12:00',
    dayIndex: 0,
    personnel: ['秦广王', '判官李明'],
    startTime: '06:00',
    endTime: '12:00'
  },
  {
    id: 2,
    department: '第五殿',
    type: 'regular',
    timeSlot: '12:00-18:00',
    dayIndex: 0,
    personnel: ['阎罗王', '黑白无常'],
    startTime: '12:00',
    endTime: '18:00'
  }
])

// 班次模板
const shiftTemplates = ref([
  {
    id: 1,
    name: '标准日班',
    startTime: '08:00',
    endTime: '18:00',
    departments: ['第一殿', '第二殿', '第三殿']
  },
  {
    id: 2,
    name: '标准夜班',
    startTime: '18:00',
    endTime: '06:00',
    departments: ['第五殿', '第九殿', '第十殿']
  },
  {
    id: 3,
    name: '紧急值班',
    startTime: '00:00',
    endTime: '24:00',
    departments: ['第五殿']
  }
])

// 时间统计
const timeStats = reactive({
  totalShifts: 28,
  coverageHours: 168,
  departments: 6
})

// 表单数据
const shiftForm = reactive({
  startTime: null,
  endTime: null,
  department: '',
  dates: [],
  type: 'regular'
})

// 表单验证规则
const shiftRules = {
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  department: [{ required: true, message: '请选择值班部门', trigger: 'change' }],
  dates: [{ required: true, message: '请选择值班日期', trigger: 'change' }]
}

// 计算属性
const currentWeekRange = computed(() => {
  const start = new Date(currentWeek.value)
  const end = new Date(start)
  end.setDate(start.getDate() + 6)
  return `${start.getMonth() + 1}月${start.getDate()}日 - ${end.getMonth() + 1}月${end.getDate()}日`
})

// 方法
const getShiftsForTimeAndDay = (timeSlot, dayIndex) => {
  return shifts.value.filter((shift) => shift.timeSlot === timeSlot && shift.dayIndex === dayIndex)
}

const showCreateShiftModal = () => {
  Object.assign(shiftForm, {
    startTime: null,
    endTime: null,
    department: '',
    dates: [],
    type: 'regular'
  })
  createShiftModalVisible.value = true
}

const handleCreateShift = async () => {
  try {
    await shiftFormRef.value.validate()
    // 创建班次逻辑
    message.success('班次创建成功')
    createShiftModalVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const editShift = (shift) => {
  message.info(`编辑班次: ${shift.department}`)
}

const applyTemplate = (template) => {
  message.success(`应用模板: ${template.name}`)
}

const previousWeek = () => {
  const newDate = new Date(currentWeek.value)
  newDate.setDate(newDate.getDate() - 7)
  currentWeek.value = newDate
}

const nextWeek = () => {
  const newDate = new Date(currentWeek.value)
  newDate.setDate(newDate.getDate() + 7)
  currentWeek.value = newDate
}

const handleViewModeChange = () => {
  message.info(`切换到${viewMode.value === 'week' ? '周' : '月'}视图`)
}

const exportSchedule = () => {
  message.info('排班表导出功能开发中...')
}

onMounted(() => {
  // 页面加载时的初始化逻辑
})
</script>

<style lang="scss" scoped>
.time-arrangement-container {
  padding: 24px;

  .arrangement-header {
    text-align: center;
    margin-bottom: 32px;

    .header-content {
      .ancient-title {
        font-size: 32px;
        font-weight: bold;
        color: $secondary-color;
        margin-bottom: 8px;
        text-shadow: 0 0 20px rgba(212, 153, 10, 0.3);
      }

      .header-subtitle {
        font-size: 16px;
        color: $text-secondary;
        letter-spacing: 2px;
      }
    }
  }

  .route-info {
    margin-bottom: 24px;
    padding: 12px 16px;
    border-radius: 8px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(212, 153, 10, 0.2);
  }

  .weekly-calendar {
    .calendar-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .time-navigation {
        display: flex;
        align-items: center;
        gap: 16px;

        .current-week {
          font-size: 16px;
          font-weight: bold;
          color: $primary-color;
        }
      }
    }

    .calendar-body {
      .schedule-table {
        width: 100%;
        border-collapse: collapse;
        border: 1px solid rgba(212, 153, 10, 0.2);

        th,
        td {
          border: 1px solid rgba(212, 153, 10, 0.2);
          text-align: center;
          vertical-align: top;
        }

        th {
          background: rgba(212, 153, 10, 0.1);
          padding: 12px 8px;
          font-weight: bold;
          color: $primary-color;
        }

        .time-cell {
          width: 120px;
          background: rgba(212, 153, 10, 0.05);
          font-weight: bold;
          color: $text-primary;
          padding: 8px;
        }

        .schedule-cell {
          height: 80px;
          padding: 4px;

          .shift-block {
            background: linear-gradient(135deg, #1890ff, #40a9ff);
            border-radius: 4px;
            padding: 8px;
            margin-bottom: 4px;
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
              transform: scale(1.05);
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            }

            &.regular {
              background: linear-gradient(135deg, #52c41a, #73d13d);
            }

            &.overtime {
              background: linear-gradient(135deg, #fa8c16, #ffa940);
            }

            &.emergency {
              background: linear-gradient(135deg, #ff4d4f, #ff7875);
            }

            .shift-info {
              color: white;
              font-size: 12px;

              .shift-department {
                font-weight: bold;
                margin-bottom: 2px;
              }

              .shift-personnel {
                opacity: 0.9;
              }
            }
          }
        }
      }
    }
  }

  .shift-templates {
    .template-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid rgba(212, 153, 10, 0.1);

      &:last-child {
        border-bottom: none;
      }

      .template-info {
        flex: 1;

        .template-name {
          margin: 0 0 4px 0;
          color: $primary-color;
          font-size: 14px;
          font-weight: bold;
        }

        .template-time {
          margin: 0 0 8px 0;
          color: $text-secondary;
          font-size: 12px;
        }

        .template-departments {
          .ant-tag {
            margin-right: 4px;
          }
        }
      }
    }
  }

  .time-stats {
    .stat-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;

      .stat-label {
        color: $text-secondary;
        font-size: 14px;
      }

      .stat-value {
        color: $secondary-color;
        font-weight: bold;
        font-size: 14px;
      }
    }
  }

  :deep(.ant-card) {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(212, 153, 10, 0.2);
    border-radius: 12px;
  }

  :deep(.ant-card-head) {
    border-bottom: 1px solid rgba(212, 153, 10, 0.2);
  }
}
</style>
